/*
 * @(#)MemoListNewAdapter.java $version 2013. 4. 5.
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.design.oop.control;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.design.oop.R;
import com.design.oop.bean.WheatBeerKind;
import com.design.oop.util.CommonUtil;

/**
 * @author kelly
 */
public class MemoListAdapter extends AbsAnimateListAdapter<ArrayList<WheatBeerKind>, WheatBeerKind> {
	protected boolean isBeingLoaded;

	protected SparseIntArray cachedItemHeights;
	protected MemoListView adapterView;
	protected LayoutInflater layoutInflater;
	protected MemoListAdapterListener itemListAdapterListener;
	protected ArrayList<WheatBeerKind> dataSource;
	private View measureView;
	private Context context;

	public MemoListAdapter(Activity activity) {
		context = activity;
		isBeingLoaded = false;
		cachedItemHeights = new SparseIntArray();
		layoutInflater = LayoutInflater.from(activity);
	}

	public int getItemHeight(int fillIndex, View itemView) {
		int height = cachedItemHeights.get(fillIndex, -1);
		//		int height = -1;
		if (height == -1) {
			View targetView;
			if (itemView == null) { //measure 모드 
				measureView = getView(fillIndex, measureView, true);
				targetView = measureView;
			} else { //일반 모드 
				targetView = itemView;
				//				measureView = itemView; //이 코드는 위험하다?!
			}
			int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(adapterView.getColumnWidth(), View.MeasureSpec.EXACTLY);
			int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.EXACTLY);
			targetView.measure(widthMeasureSpec, heightMeasureSpec);

			height = targetView.getMeasuredHeight();
			cachedItemHeights.put(fillIndex, height);
		}
		return height;
	}

	@SuppressLint("NewApi")
	public View getView(int position, View convertView, boolean forMeasure) {
		final ItemHolder holder;
		final WheatBeerKind item = (WheatBeerKind)getItem(position);

		if (convertView == null) {
			convertView = layoutInflater.inflate(R.layout.beer_list_item, null, false);

			holder = new ItemHolder();
			holder.imageCell = (ImageView)convertView.findViewById(R.id.image_cell);
			holder.imageCell.setOnClickListener(onClickListener);
			convertView.setOnClickListener(onClickListener);
			convertView.setTag(holder);
		} else {
			holder = (ItemHolder)convertView.getTag();
		}

		convertView.clearAnimation();

		if (item != null) {
			setItem(holder, item);
			if (!forMeasure) {
				loadMore(position); // UI thread를 쓴 데이터 로드임.
			}
		}
		return convertView;
	}

	/**
	 * @param holder
	 * @param item
	 */
	@SuppressLint("NewApi")
	public void setItem(final ItemHolder holder, final WheatBeerKind item) {
		setItemImage(holder, item);
	}

	private void setItemImage(final ItemHolder holder, final WheatBeerKind item) {
		final int columnWidth = adapterView.getColumnWidth();
		holder.imageCell.setMinimumWidth(columnWidth);

		final int imageHeight = item.getImageHeight(columnWidth);
		holder.imageCell.setMinimumHeight(imageHeight);
		holder.imageCell.setScaleType(ScaleType.CENTER);

		holder.imageCell.setImageResource(R.drawable.ic_menu_refresh_holo_light);
		final Animation animation = AnimationUtils.loadAnimation(context, R.anim.rotate);
		holder.imageCell.clearAnimation();
		holder.imageCell.startAnimation(animation);

		if (holder.imageTask != null && !holder.imageTask.isCancelled()) {
			holder.imageTask.cancel(true);
			holder.imageTask = null;
		}

		holder.imageCell.setScaleType(ScaleType.FIT_XY);
		animation.cancel();
		holder.imageCell.clearAnimation();

		Bitmap bitmap = com.design.oop.util.ImageUtil.decodeSampledBitmapForThumbnail(item.getImageUrl(), columnWidth, imageHeight);
		holder.imageCell.setImageBitmap(bitmap);
		holder.imageCell.setTag(item.getDrawableId());
	}

	View.OnClickListener onClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			int drawableId = (Integer)view.getTag();
			itemListAdapterListener.onClickItem(drawableId);
		}
	};

	public class ItemHolder {
		public ImageView imageCell;
		public AsyncTask<String, Void, Bitmap> imageTask;
	}

	@Override
	public int getCount() {
		return dataSource == null || CommonUtil.isEmptyList(dataSource) ? 0 : dataSource.size();
	}

	@Override
	public Object getItem(int position) {
		if (CommonUtil.isEmptyList(dataSource)) {
			return null;
		}
		return position > dataSource.size() - 1 ? null : dataSource.get(position);
	}

	@Override
	public long getItemId(int position) {
		return (long)position;
	}

	public boolean isNotEmpty() {
		return dataSource != null && CommonUtil.isNotEmptyList(dataSource) && dataSource.size() > 0;
	}

	public ArrayList<WheatBeerKind> getDataSource() {
		return dataSource;
	}

	public void setDataSource(ArrayList<WheatBeerKind> itemList) {
		//		convertViewList.clear();
		dataSource = itemList;
		notifyDataSetChanged();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		return getView(position, convertView, false);
	}

	public void setItemListView(MemoListView adapterView) {
		this.adapterView = adapterView;
	}

	protected void loadMore(int i) {
		// adapter에 남은 메모가 10개일때 추가 로드 
		int threshold = Math.max(getCount() - 10, 0);
		if (itemListAdapterListener != null && i == threshold && !isBeingLoaded) {
			itemListAdapterListener.loadMoreData();
			isBeingLoaded = true;
		}
	}

	public void finishLoading() {
		isBeingLoaded = false;
	}

	public void setItemListAdapterListener(MemoListAdapterListener itemListAdapterListener) {
		this.itemListAdapterListener = itemListAdapterListener;
	}

	public void resetCachedItemHeights() {
		cachedItemHeights.clear();
	}

	public static interface MemoListAdapterListener {
		public void loadMoreData();

		public void onClickItem(int contentId);

		public void onImportantCheckedItem(long contentId, boolean isChecked);
		//		public void onLongClickItem(long contentId);
	}

	public void remove(int index) { //아이템 삭제시
		if (dataSource != null) {
			dataSource.remove(index);
			cachedItemHeights.clear();
		}
	}

	/**
	 * @return
	 * @see com.campmobile.android.sherbet.ui.adapter.AbsAnimateListAdapter#isEmpty()
	 */
	@Override
	public boolean isEmpty() {
		if (dataSource == null || CommonUtil.isEmptyList(dataSource)) {
			return true;
		}
		return false;
	}

	/**
	 * @param position
	 * @param item
	 * @see com.campmobile.android.sherbet.ui.adapter.AbsAnimateListAdapter#addItem(int, java.lang.Object)
	 */
	@Override
	public void addItem(int position, WheatBeerKind item) {
		if (dataSource == null) {
			dataSource = new ArrayList<WheatBeerKind>();
		}
		dataSource.add(position, item);
	}

}
